package com.youkeda.test.http;

import com.alibaba.fastjson.JSON;
import okhttp3.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author xshuai
 */
public class JsonPoster {
    public static final MediaType JSON_TYPE = MediaType.parse("application/json;charset=utf-8");

    public static void main(String[] args) {
        String url = "https://www.fastmock.site/mock/3d95acf3f26358ef032d8a23bfdead99/api/posts";
        Map<String, String> datas = new HashMap<String, String>();
        datas.put("num", "20190101");
        datas.put("name", "王陆");
        datas.put("gender", "男");
        datas.put("faculty", "灵剑派");
        datas.put("discipline", "无相剑骨");
        datas.put("class", "一年一班");
        datas.put("startYear", "2019");
        JsonPoster poster = new JsonPoster();
        String content = poster.postContent(url, datas);
        System.out.println("API调用结果");
        System.out.println(content);
    }

    public String postContent(String url, Map<String, String> datas) {
        OkHttpClient okHttpClient = new OkHttpClient();
        String param = JSON.toJSONString(datas);
        RequestBody requestBody = RequestBody.create(param, JSON_TYPE);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        Call call = okHttpClient.newCall(request);
        String result = null;
        try {
            result = call.execute().body().string();
        } catch (Exception e) {
            System.out.println("request" + url + "error.");
            e.printStackTrace();
        }
        return result;
    }
}
